package webgamemaker.Editor;

import java.util.ArrayList;

import webgamemaker.Common.Callback;
import webgamemaker.Editor.FileNavigator.FileNode;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.CellDoubleClickEvent;
import com.smartgwt.client.widgets.grid.events.CellDoubleClickHandler;


public class FileNavigatorWindow extends Window 
{
	public String selectedFile;
	public ArrayList<Callback> listCallback;
	
	public FileNavigatorWindow(String baseDir)
	{
		listCallback = new ArrayList<Callback>();
		setTitle("open file");
		setIsModal(true);
		setShowModalMask(true);
		centerInPage();
		setWidth(500);  
		setHeight(500); 
		final Button openButton = new Button("open");
		openButton.setAlign(Alignment.CENTER);
		openButton.setDisabled(true);
		FileNavigator fileNavigator = new FileNavigator(baseDir);
		fileNavigator.addCellClickHandler(new CellClickHandler()
			{
				public void onCellClick(CellClickEvent event) 
				{
					if(event.getRecord() instanceof FileNode)
					{
						FileNode fileNode = (FileNode) event.getRecord();
						if(!fileNode.isDir)
						{
							openButton.setDisabled(false);
							selectedFile = fileNode.path+"/"+fileNode.name;
						}
						else openButton.setDisabled(true);
					}
				}
				
			});
		fileNavigator.addCellDoubleClickHandler(new CellDoubleClickHandler()
		{
			public void onCellDoubleClick(CellDoubleClickEvent event) 
			{
				if(event.getRecord() instanceof FileNode)
				{
					FileNode fileNode = (FileNode) event.getRecord();
					if(!fileNode.isDir)
					{
						selectedFile = fileNode.path+"/"+fileNode.name;
						openButton.action();
					}
				}
			}
		});
		addItem(fileNavigator);
		addItem(openButton);
		this.addCloseClickHandler(new CloseClickHandler()
			{
				public void onCloseClick(CloseClientEvent event) 
				{
					FileNavigatorWindow.this.destroy();
				}
			});
		openButton.addClickHandler(new ClickHandler()
			{
				public void onClick(ClickEvent event) 
				{
					for(Callback callback : listCallback)
						callback.onCall(FileNavigatorWindow.this);
					FileNavigatorWindow.this.destroy();
				}
			});
	}
	
	public void addCallback(Callback callback)
	{
		listCallback.add(callback);
	}
}
